<template>
  <div class="chat-container">
    <!-- 聊天消息区 -->
    <div class="chat-messages" ref="messagesContainer">
      <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.role]"
      >
        <div class="message-header">
          <!-- 用户消息：头像在前，时间在后 -->
          <template v-if="message.role === 'user'">
            <div
                :class="['message-avatar', {'user-avatar': message.role === 'user'}]"
            >
              {{ message.role === "user" ? "👤" : "🤖" }}
            </div>
            <div class="message-time">{{ message.timestamp }}</div>
          </template>
          <!-- 助手消息：头像在前，时间在后 -->
          <template v-else>
            <div
                :class="['message-avatar', {'assistant-avatar': message.role === 'assistant'}]"
            >
              {{ message.role === "user" ? "👤" : "🤖" }}
            </div>
            <div class="message-time">{{ message.timestamp }}</div>
          </template>
        </div>
        <div class="message-content-wrapper">
          <div class="message-content" v-html="message.content"></div>
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="chat-input">
      <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
      />
      <button @click="sendMessage" :disabled="isLoading">
        {{ isLoading ? "发送中..." : "发送" }}
      </button>
    </div>
  </div>
</template>

<script>
import { chatDeepSeek } from "@/network/ai/deepseep";
import marked from 'marked'; // 引入 marked 库

export default {
  data() {
    return {
      messages: JSON.parse(localStorage.getItem('deepseek-chat-messages')) || [],
      inputMessage: '',
      isLoading: false
    };
  },
  watch: {
    messages: {
      handler(newVal) {
        localStorage.setItem('deepseek-chat-messages', JSON.stringify(newVal));
      },
      deep: true
    }
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return;

      const messageContent = this.inputMessage;
      const userMessage = {
        role: "user",
        content: messageContent,
        timestamp: new Date().toLocaleString()
      };
      this.messages.push(userMessage);
      this.inputMessage = "";
      this.scrollToBottom();

      this.isLoading = true;
      try {
        const chatMessage = {
          prompt: messageContent
        };
        const res = await chatDeepSeek(chatMessage);
        if (res.code !== '0') {
          this.$message.error(res.msg);
        } else {
          let rawContent = marked(res.result.message);
          this.messages.push({
            role: "assistant",
            content: rawContent,
            timestamp: new Date().toLocaleString()
          });
        }
      } catch (error) {
        console.error("API 请求失败:", error);
        this.messages.push({
          role: "assistant",
          content: "抱歉，出错了，请稍后重试！",
          timestamp: new Date().toLocaleString()
        });
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        container.scrollTop = container.scrollHeight;
      });
    }
  },
  mounted() {
    this.scrollToBottom();
  }
};
</script>

<style scoped>
/* 基础样式 */
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #f5f5f5;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.message {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

.message-header {
  display: flex;
  align-items: center;
}

.message-avatar {
  font-size: 24px;
  margin-right: 10px;
}

.user .message-avatar {
  margin-left: auto;
  margin-right: 10px;
}

.message-time {
  font-size: 12px;
  color: #888;
}

.user .message-header {
  justify-content: flex-end;
}

.assistant .message-header {
  justify-content: flex-start;
}

.message-content-wrapper {
  display: flex;
  flex-direction: column;
}

.message-content {
  padding: 10px 15px;
  border-radius: 8px;
  max-width: 80%;
}

.user .message-content {
  background: #e3f2fd;
  align-self: flex-end;
}

.assistant .message-content {
  background: #f1f1f1;
  align-self: flex-start;
}

.chat-input {
  display: flex;
  gap: 10px;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.chat-input button {
  padding: 10px 20px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-input button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}
</style>